import 'dart:convert';
import 'package:flutter/material.dart';
import './tool_button_data.dart';
import './tool_button_widget.dart';
import 'data.dart';
import '../../../../widgets/common_image.dart';
import '../../../../utils/event_bus.dart';
import '../../../config.dart';
import '../../../model/book.dart';
import '../../../utils/store.dart';
import '../../../provide/book.dart';

class TabBookShelf extends StatefulWidget {
  const TabBookShelf({Key? key}) : super(key: key);

  @override
  State<TabBookShelf> createState() => _TabBookShelfState();
}

class _TabBookShelfState extends State<TabBookShelf> {
  bool isShowDelBtn = false;
  bool checkBoxValue = false;
  List<BookModel> bookInfoDatas = [];
  bool isAllCheck = true;

  @override
  void initState() {
    super.initState();
    setState(() {
      bookInfoDatas = bookInfoData;
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  @override
  void dispose() {
    super.dispose();
    remove(StoreKeys.booInfo);
  }

  /// 删除持久化数据中某个key
  remove(StoreKeys key) async {
    Store store = await Store.getInstance();
    store.remove(key);
  }

  getBookInfo() async {
    List<BookModel> boolList = [];
    Store store = await Store.getInstance();
    var bookInfo = await store.getString(StoreKeys.booInfo);
    bookInfo = json.decode(bookInfo);
    for (int index = 0; index < bookInfo.length; index++) {
      boolList.add(BookModel.fromJson(bookInfo[index]));
    }
    setState(() {
      bookInfoDatas = boolList;
    });
  }

  changeCheckBox(String bookId) async {
    Store store = await Store.getInstance();
    var bookInfo = await store.getString(StoreKeys.booInfo);
    bookInfo = json.decode(bookInfo);
    //遍历当前点击的item
    for (int index = 0; index < bookInfo.length; index++) {
      if (bookInfo[index]['bookId'] == bookId) {
        bookInfo[index]['ischeck'] = !bookInfo[index]['ischeck'];
        break;
      }
    }
    //重新持久化
    bookInfo = json.encode(bookInfo).toString();
    await store.setString(StoreKeys.booInfo, bookInfo);
    await getBookInfo();
  }

  //全选按钮效果的实现
  changeAllCheckSate(bool isCheck) async {
    Store store = await Store.getInstance();
    var bookInfo = await store.getString(StoreKeys.booInfo);
    bookInfo = json.decode(bookInfo);
    //遍历当前点击的item
    for (int index = 0; index < bookInfo.length; index++) {
      bookInfo[index]['ischeck'] = isCheck;
    }
    //重新持久化
    bookInfo = json.encode(bookInfo).toString();
    await store.setString(StoreKeys.booInfo, bookInfo);
    await getBookInfo();
  }

  // 无数据
  Widget noBookShelf(BuildContext context) {
    return Center(
      child: GestureDetector(
        onTap: () {
          eventBus.emit(Config.EventToggleTabBarIndex, 1);
          // CommonToast.showToast('请到书城添加书籍！');
        },
        child: Text('您的书架空空如也，快去书城添加吧！'),
      ),
    );
  }

  //有数据
  Widget haveBookShelf(BuildContext context) {
    return Padding(
      padding: EdgeInsets.only(top: 10.0, bottom: 60, left: 10.0, right: 10.0),
      child: ListView.builder(
        itemBuilder: (context, index) {
          return Container(
            height: 115.0,
            decoration: BoxDecoration(
                border:
                    Border(bottom: BorderSide(width: 1.0, color: Colors.grey))),
            child: Row(
              children: [
                Container(
                    width: 100.0,
                    height: 100.0,
                    child: CommonImage(bookInfoDatas[index].bookImgUrl!)),
                Expanded(
                    child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      bookInfoDatas[index].title!,
                      style: TextStyle(fontSize: 20.0),
                    ),
                    Text(
                      bookInfoDatas[index].subTitle!,
                      style: TextStyle(fontSize: 16.0, color: Colors.grey),
                    ),
                    Row(
                      children: [
                        Icon(
                          Icons.timelapse_outlined,
                          color: Colors.grey,
                          size: 12.0,
                        ),
                        Padding(
                          padding: EdgeInsets.only(left: 5.0),
                          child: Text(
                            bookInfoDatas[index].updatetime!,
                            style: TextStyle(
                                fontSize: 12.0, color: Colors.grey.shade600),
                          ),
                        )
                      ],
                    ),
                  ],
                )),
                isShowDelBtn
                    ? Container(
                        child: Center(
                        child: IconButton(
                          onPressed: () {
                            changeCheckBox(bookInfoDatas[index].bookId!);
                          },
                          icon: Icon(bookInfoDatas[index].ischeck!
                              ? Icons.check_box_rounded
                              : Icons.check_box_outline_blank),
                        ),
                      ))
                    : Container()
              ],
            ),
          );
        },
        itemCount: bookInfoDatas.length,
      ),
    );
  }

  Future<String> _getBookInfo(BuildContext context) async {
    return 'end';
  }

  /// @description: 工具栏
  /// @param {context} context
  /// @return {mixed}
  void showBottomSheet(context) {
    showModalBottomSheet(
        backgroundColor: Colors.transparent,
        context: context,
        builder: (BuildContext context) {
          return buildBottomSheetWidget(context);
        });
  }

  Widget buildBottomSheetWidget(BuildContext context) {
    var width = (MediaQuery.of(context).size.width - 18);

    return Container(
      margin: EdgeInsets.all(5.0),
      height: 300.0,
      child: Column(
        children: [
          Container(
            height: 240.0,
            decoration: BoxDecoration(
                color: Colors.white, borderRadius: BorderRadius.circular(10.0)),
            margin: EdgeInsets.only(bottom: 20.0),
            padding: EdgeInsets.only(top: 36.0),
            child: Center(
              child: Column(
                children: [
                  Container(
                    height: 83.0,
                    width: width,
                    decoration: BoxDecoration(
                        border: Border(
                            bottom:
                                BorderSide(width: 1.0, color: Colors.grey))),
                    child: Row(
                      children: [
                        // ToolButtonWidget(ButtonDataList[0]),
                        ToolButtonWidget(ToolButtonData('整理书架', '', (context) {
                          setState(() {
                            isShowDelBtn = !isShowDelBtn;
                          });
                          eventBus.emit(Config.BottomNavigationBar,
                              Config.BottomNavigationBarBottom);
                          Navigator.of(context).pop();
                        }, suffix: Icons.manage_accounts)),
                        SizedBox(
                          width: 1,
                          height: 83,
                          child: DecoratedBox(
                            decoration: BoxDecoration(color: Colors.grey),
                          ),
                        ),
                        ToolButtonWidget(ButtonDataList[1]),
                        SizedBox(
                          width: 1,
                          height: 83,
                          child: DecoratedBox(
                            decoration: BoxDecoration(color: Colors.grey),
                          ),
                        ),
                        ToolButtonWidget(ButtonDataList[2])
                      ],
                    ),
                  ),
                  Container(
                    height: 83.0,
                    width: width,
                    child: Row(
                      children: [
                        Container(
                          margin: EdgeInsets.only(top: 20.0),
                          child: ToolButtonWidget(ButtonDataList[3]),
                        ),
                        SizedBox(
                          width: 1,
                          height: 83,
                          child: DecoratedBox(
                            decoration: BoxDecoration(color: Colors.grey),
                          ),
                        ),
                        Container(
                          margin: EdgeInsets.only(top: 20.0),
                          child: ToolButtonWidget(ButtonDataList[4]),
                        ),
                        SizedBox(
                          width: 1,
                          height: 83,
                          child: DecoratedBox(
                            decoration: BoxDecoration(color: Colors.grey),
                          ),
                        ),
                        Container(
                          margin: EdgeInsets.only(top: 20.0),
                          child: ToolButtonWidget(ButtonDataList[5]),
                        ),
                      ],
                    ),
                  )
                ],
              ),
            ),
          ),
          GestureDetector(
            onTap: () {
              eventBus.emit(Config.BottomNavigationBar, 0.0);
              Navigator.of(context).pop();
            },
            child: Container(
              height: 40.0,
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(10.0)),
              child: Center(
                child: Text("取消"),
              ),
            ),
          )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('书架'),
        leading: isShowDelBtn
            ? Container()
            : IconButton(
                onPressed: () {
                  showBottomSheet(context);
                },
                icon: Icon(Icons.list_outlined),
                iconSize: 24.0,
              ),
        actions: [
          isShowDelBtn
              ? GestureDetector(
                  onTap: () {
                    eventBus.emit(Config.BottomNavigationBar, 0.0);
                    setState(() {
                      this.isShowDelBtn = !isShowDelBtn;
                    });
                  },
                  child: Center(
                      child: Text(
                    '完成',
                    style: TextStyle(fontSize: 20.0, color: Colors.white),
                  )))
              : IconButton(
                  onPressed: () {}, icon: Icon(Icons.search), iconSize: 24.0)
        ],
      ),
      body: Stack(
        fit: StackFit.expand,
        children: [
          haveBookShelf(context),
          Container(
            height: 200,
          ),
          isShowDelBtn
              ? Positioned(
                  bottom: 0,
                  child: Container(
                    width: MediaQuery.of(context).size.width,
                    height: 50.0,
                    decoration: BoxDecoration(
                        color: Colors.white,
                        border: Border(
                            top: BorderSide(
                                width: 1.0, color: Colors.grey.shade400))),
                    child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: [
                          GestureDetector(
                            onTap: () {
                              setState(() {
                                this.checkBoxValue = !checkBoxValue;
                              });
                              changeAllCheckSate(checkBoxValue);
                            },
                            child: Row(
                              children: [
                                Icon(checkBoxValue
                                    ? Icons.check_box_rounded
                                    : Icons.check_box_outline_blank),
                                Text(checkBoxValue ? '取消全选' : '全选')
                              ],
                            ),
                          ),
                          GestureDetector(
                            onTap: () {},
                            child: Row(
                              children: [Icon(Icons.delete), Text('删除')],
                            ),
                          ),
                          GestureDetector(
                            onTap: () {},
                            child: Row(
                              children: [
                                Icon(Icons.move_to_inbox),
                                Text('移至分组')
                              ],
                            ),
                          )
                        ]),
                  ),
                )
              : Container(),
          Container(
            height: 200,
          ),
        ],
      ),
    );
  }
}
